<template>
    <div id="mysql" >
    </div>
</template>

<script>
export default {
    name: 'MySQL',
    props: {
        record: {}, // 成绩数据
    },
    data () {
        return {
            db: null, //数据库
        }
    },
    mounted () {
        // 初始化
        this.init()
    },
    methods: {
        init () {
            if(!window.openDatabase){
                console.warn("不支持WebSql本地存储！");
                return;
            }
            // openDatabase()方法打开已存在的数据库，如果数据库不存在，则会创建一个新的数据库
            this.db = openDatabase('ming', '1.0', '游戏成绩缓存', 2 * 1024 * 1024);

            if(!this.db){
                console.warn("数据库创建失败！");
                return;
            }else{
                console.log("本地数据库创建成功！");
            }
            /**
             * 如果记录表不存在，则创建
             * 
             * id 记录的唯一标识，方便更新
             * username 用户名
             * space_name 区间名
             * times_kill = 击杀次数
             * times_killed 被击杀次数
             * size 分数
             * create_time 创建时间
             * update_time 更新时间
             */
            this.db.transaction(function (tx) {  
                tx.executeSql('CREATE TABLE IF NOT EXISTS RECORD (id unique, username, space_name, times_kill, times_killed, size, create_time, update_time)');
            });
            this.save();
        },
        save () {
            if(!this.db){
                console.warn("本地数据库不存在！！！")
                return;
            }
            let record = this.record;
            let id = record['id'];
            let len = 0;
            this.db.transaction(function (tx) {
                // 根据ID查询看是否有记录
                tx.executeSql('SELECT * FROM RECORD WHERE id = ?', [id], function (tx, results) {
                    len = results.rows.length;
                    console.log('查询出数据【', len, '】条，正常应该查出0条或者1条。')
                }, null);
                if(len == 0){
                    // 没有数据，插入数据
                    tx.executeSql(`
                            INSERT INTO RECORD 
                            (id, username, space_name, times_kill, times_killed, size, create_time, update_time) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                        `, [record['id'], record['username'], record['space_name'], record['times_kill'], record['times_killed'], record['size'], record['create_time'], record['update_time']]
                    );
                }else{
                    // 已有数据，更新数据
                    tx.executeSql(`
                            UPDATE RECORD SET 
                            times_kill=?, times_killed=?, size=?, update_time=?
                            WHERE id=?
                        `, [ record['times_kill'], record['times_killed'], record['size'], record['update_time'], record['id'] ]
                    );
                }
            });
        },
    },
    unmounted () {

    }
}
</script>

<style></style>